<!--
 * @Descripttion: 
 * @Author: Kevin
 * @Date: 2022-06-14 10:58:57
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-07-13
-->
<template>
  <div>
    <div class="config-wrapper">
      <a-tabs
        v-model="activeKey"
        style="text-align: left"
        @change="onChangeTab"
      >
        <a-tab-pane :tab="$t('thirdPart.config')" :key="1">
          <SourceForm
            @saveForm="onSave"
            :record="thirdPartForm"
            ref="sourceFormRef"
          />
        </a-tab-pane>
        <a-tab-pane :tab="$t('thirdPart.policyMap')" :key="2">
          <MappingForm
            @saveForm="onSave"
            :record="thirdPartForm"
            ref="mappingFormRef"
          />
        </a-tab-pane>
      </a-tabs>

      <!-- <div slot="foot" class="add-footer">
        <div class="btn-wrapper">
          <a-button @click="onClose">
            {{ $t('common.cancel') }}
          </a-button> 
          <a-button type="primary" @click="onSave">
            {{ $t('common.save') }}
          </a-button>
        </div>
      </div>-->
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import SourceForm from '../sourceForm.vue';
import MappingForm from '../mappingForm.vue';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
import { requestHttp, maccApi } from '@utils/index';
import lodash from 'lodash';
export default {
  name: 'thirdPartEditor',
  mixins: [authSysMixin],
  components: {
    SourceForm,
    MappingForm,
  },
  props: {
    record: {
      typeof: Object,
      default: () => {
        return null;
      },
    },
  },
  data() {
    return {
      steps: [this.$t('thirdPart.config'), this.$t('thirdPart.policyMap')],
      activeKey: 1,
      previousKey: 1,
      isVisible: true, // false tommy 24.6.3设置为默认可视
      thirdPartForm: {}, // 用于编辑时赋值
    };
  },
  watch: {
    record: {
      handler(value) {
        this.thirdPartForm = lodash.cloneDeep(value);
        this.$store.commit(
          'AuthCommon/SET_3RD_SOURCE_FORM',
          this.thirdPartForm
        );
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {},
  methods: {
    async onChangeTab() {
      if (this.previousKey === 1) {
        const sourceForm = await this.$refs.sourceFormRef.getModel();
        this.$store.commit('AuthCommon/SET_3RD_SOURCE_FORM', sourceForm);
        if (!sourceForm) {
          this.activeKey = this.previousKey;
          this.$message.warning(this.$t('thirdPart.sourceTip'));
          return false;
        }
        if (!sourceForm.status) {
          this.activeKey = this.previousKey;
          this.$message.warning(this.$t('thirdPart.sourceEnableTip'));
          return false;
        }
      } else if (this.previousKey === 2) {
        const mappingForm = await this.$refs.mappingFormRef.getModel();
        if (!mappingForm) {
          this.activeKey = this.previousKey;
          this.$message.warning(this.$t('thirdPart.mappingTip'));
          return false;
        }
      }
      this.previousKey = this.activeKey;
    },

    openEditor(rowRecord) {
      this.thirdPartForm = lodash.cloneDeep(rowRecord);
      this.isVisible = true;
    },
    onClose() {
      this.isVisible = false;
    },
    async onSave() {
      const tempForm = lodash.cloneDeep(this.thirdPartForm);

      if (this.$refs.sourceFormRef) {
        const sourceForm = await this.$refs.sourceFormRef.getModel();
        this.$store.commit('AuthCommon/SET_3RD_SOURCE_FORM', sourceForm);
        if (!sourceForm) {
          this.activeKey = 1; // tommy 24.6.3 没有数据的时候用户直接保存

          return false;
        }

        tempForm.name = sourceForm.name;
        tempForm.type = sourceForm.type;
        tempForm.serverDomain = sourceForm.serverDomain;
        tempForm.serverIp = sourceForm.serverIp;
        tempForm.serverPort = sourceForm.serverPort;
        tempForm.rootDn = sourceForm.rootDn;
        tempForm.adminName = sourceForm.adminName;
        tempForm.adminPwd = sourceForm.adminPwd;
        tempForm.status = sourceForm.status;
        delete tempForm.statusBool;
        if (sourceForm.type === 'ldap') {
          tempForm.serverIp = sourceForm.ldapIp;
          tempForm.serverPort = sourceForm.ldapPort;
          tempForm.userNameAttr = sourceForm.userNameAttr;
          tempForm.userPwdAttr = sourceForm.userPwdAttr;
          tempForm.userPwdType = sourceForm.userPwdType;
        }

        // 不切换tab直接请求的情况
        const tempList = [];
        if (
          tempForm.accountSourceProfileList &&
          tempForm.accountSourceProfileList.length > 0
        ) {
          this.loopOverTreeHasPolicy(
            {
              children: tempForm.accountSourceProfileList,
            },
            tempList
          );
        }
        tempForm.accountSourceProfileList = tempList;
      }

      if (this.$refs.mappingFormRef) {
        const mappingForm = await this.$refs.mappingFormRef.getModel();
        if (!mappingForm) {
          this.activeKey = 2; // tommy 24.6.3 没有数据的时候用户直接保存
          return false;
        }

        tempForm.defaultProfileId = mappingForm.defaultProfileId;
        tempForm.syncType = mappingForm.syncType;
        tempForm.syncLevel = mappingForm.syncLevel;
        tempForm.accountSourceProfileList =
          mappingForm.accountSourceProfileList;
      }

      delete tempForm.accountSourceProfileIdList;
      this.save3rdSource(tempForm);
    },

    loopOverTreeHasPolicy(treeData, tempList) {
      console.log('loop ' + treeData.name);
      if (treeData.profileId) {
        tempList.push({
          name: treeData.name,
          profileId: treeData.profileId,
          dn: treeData.dn, // tommy 240713 什么时候加的？
          level: treeData.level,
        });
      }
      if (treeData.children) {
        treeData.children.forEach((child) => {
          this.loopOverTreeHasPolicy(child, tempList);
        });
      }
    },

    async save3rdSource(tempForm) {
      let api = maccApi.MACC_SOURCE_UPDATE_PUT_API;
      let method = 'PUT';
      if (!tempForm.id) {
        api = maccApi.MACC_SOURCE_ADD_POST_API;
        method = 'POST';
      }

      const res = await this.requestHttpAuth({
        api,
        method,
        params: tempForm,
      });
      if (res?.data?.success) {
        this.$message.success(this.$t('common.editSuccess'));
        // this.$emit('refreshList');
        // this.onClose();
      } else {
        this.$message.warning(res?.data?.message || this.$t('common.optFail'));
      }
    },
  },
};
</script>

<style lang="less" scoped>
.btn-wrapper {
  display: flex;
  gap: 16px;
  margin-top: 8px;
  margin-left: 250px;
}
</style>
